package controller

import (
	"net/http"
	"strconv"

	"github.com/example/video_backend/internal/model"
	"github.com/example/video_backend/internal/service"
	"github.com/example/video_backend/pkg/logger"
	"github.com/gin-gonic/gin"
)

// CommentController 评论控制器
type CommentController struct {
	commentService service.CommentService
}

// NewCommentController 创建评论控制器实例
func NewCommentController(commentService service.CommentService) *CommentController {
	return &CommentController{commentService: commentService}
}

// AddComment 添加评论
type AddCommentRequest struct {
	Content   string `json:"content" binding:"required,min=1,max=500"`
	ReplyToID uint   `json:"reply_to_id"` // 回复的评论ID，可选
}

// @Summary 添加评论
// @Description 对视频添加评论或回复其他评论
// @Tags 评论
// @Accept json
// @Produce json
// @Security Bearer
// @Param video_id path int true "视频ID"
// @Param request body AddCommentRequest true "添加评论请求参数"
// @Success 200 {object} Response{data=model.Comment}
// @Router /api/v1/videos/{video_id}/comments [post]
func (c *CommentController) AddComment(ctx *gin.Context) {
	// 从上下文中获取用户ID
	userID, exists := ctx.Get("userID")
	if !exists {
		ctx.JSON(http.StatusUnauthorized, Response{Code: 401, Message: "未登录"})
		return
	}

	uid, ok := userID.(uint)
	if !ok {
		ctx.JSON(http.StatusUnauthorized, Response{Code: 401, Message: "无效的用户ID"})
		return
	}

	// 获取视频ID
	videoID, err := strconv.ParseUint(ctx.Param("video_id"), 10, 64)
	if err != nil {
		ctx.JSON(http.StatusBadRequest, Response{Code: 400, Message: "无效的视频ID"})
		return
	}

	var req AddCommentRequest
	if err := ctx.ShouldBindJSON(&req); err != nil {
		logger.Error("Add comment request binding error: " + err.Error())
		ctx.JSON(http.StatusBadRequest, Response{Code: 400, Message: err.Error()})
		return
	}

	err = c.commentService.AddComment(ctx, &model.Comment{
		UserID:    uid,
		VideoID:   uint(videoID),
		Content:   req.Content,
		ReplyToID: req.ReplyToID,
	})

	if err != nil {
		logger.Error("Add comment error: " + err.Error())
		ctx.JSON(http.StatusInternalServerError, Response{Code: 500, Message: err.Error()})
		return
	}

	ctx.JSON(http.StatusOK, Response{Code: 200, Message: "评论成功"})
}

// GetComments 获取视频评论列表
type GetCommentsRequest struct {
	Page     int  `form:"page,default=1" binding:"gt=0"`
	PageSize int  `form:"page_size,default=10" binding:"gt=0,lt=100"`
	ParentID uint `form:"parent_id"` // 父评论ID，用于获取回复
}

// @Summary 获取视频评论列表
// @Description 获取视频的评论列表，可选择获取特定评论的回复
// @Tags 评论
// @Accept json
// @Produce json
// @Param video_id path int true "视频ID"
// @Param page query int false "页码，默认1"
// @Param page_size query int false "每页数量，默认10，最大100"
// @Param parent_id query int false "父评论ID，用于获取回复"
// @Success 200 {object} Response{data=map[string]interface{}}
// @Router /api/v1/videos/{video_id}/comments [get]
func (c *CommentController) GetComments(ctx *gin.Context) {
	// 获取视频ID
	videoID, err := strconv.ParseUint(ctx.Param("video_id"), 10, 64)
	if err != nil {
		ctx.JSON(http.StatusBadRequest, Response{Code: 400, Message: "无效的视频ID"})
		return
	}

	var req GetCommentsRequest
	if err := ctx.ShouldBindQuery(&req); err != nil {
		logger.Error("Get comments request binding error: " + err.Error())
		ctx.JSON(http.StatusBadRequest, Response{Code: 400, Message: err.Error()})
		return
	}

	comments, total, err := c.commentService.GetCommentsByVideoID(ctx, uint(videoID), req.Page, req.PageSize)
	if err != nil {
		logger.Error("Get comments error: " + err.Error())
		ctx.JSON(http.StatusInternalServerError, Response{Code: 500, Message: err.Error()})
		return
	}

	response := map[string]interface{}{
		"list":      comments,
		"total":     total,
		"page":      req.Page,
		"page_size": req.PageSize,
	}

	ctx.JSON(http.StatusOK, Response{Code: 200, Message: "获取成功", Data: response})
}

// DeleteComment 删除评论
// @Summary 删除评论
// @Description 删除自己的评论
// @Tags 评论
// @Accept json
// @Produce json
// @Security Bearer
// @Param id path int true "评论ID"
// @Success 200 {object} Response
// @Router /api/v1/comments/{id} [delete]
func (c *CommentController) DeleteComment(ctx *gin.Context) {
	// 从上下文中获取用户ID
	userID, exists := ctx.Get("userID")
	if !exists {
		ctx.JSON(http.StatusUnauthorized, Response{Code: 401, Message: "未登录"})
		return
	}

	_, ok := userID.(uint)
	if !ok {
		ctx.JSON(http.StatusUnauthorized, Response{Code: 401, Message: "无效的用户ID"})
		return
	}

	// 获取评论ID
	commentID, err := strconv.ParseUint(ctx.Param("id"), 10, 64)
	if err != nil {
		ctx.JSON(http.StatusBadRequest, Response{Code: 400, Message: "无效的评论ID"})
		return
	}

	if err := c.commentService.DeleteComment(ctx, uint(commentID)); err != nil {
		logger.Error("Delete comment error: " + err.Error())
		ctx.JSON(http.StatusInternalServerError, Response{Code: 500, Message: err.Error()})
		return
	}

	ctx.JSON(http.StatusOK, Response{Code: 200, Message: "删除成功"})
}

// LikeComment 点赞/取消点赞评论
// @Summary 点赞/取消点赞评论
// @Description 对评论进行点赞或取消点赞
// @Tags 评论
// @Accept json
// @Produce json
// @Security Bearer
// @Param id path int true "评论ID"
// @Success 200 {object} Response
// @Router /api/v1/comments/{id}/like [post]
func (c *CommentController) LikeComment(ctx *gin.Context) {
	// 从上下文中获取用户ID
	userID, exists := ctx.Get("userID")
	if !exists {
		ctx.JSON(http.StatusUnauthorized, Response{Code: 401, Message: "未登录"})
		return
	}

	_, ok := userID.(uint)
	if !ok {
		ctx.JSON(http.StatusUnauthorized, Response{Code: 401, Message: "无效的用户ID"})
		return
	}

	// 获取评论ID
	commentID, err := strconv.ParseUint(ctx.Param("id"), 10, 64)
	if err != nil {
		ctx.JSON(http.StatusBadRequest, Response{Code: 400, Message: "无效的评论ID"})
		return
	}

	err = c.commentService.LikeComment(ctx, uint(commentID))
	message := "点赞成功"

	if err != nil {
		message = "取消点赞成功"
		logger.Error("Like comment error: " + err.Error())
		ctx.JSON(http.StatusInternalServerError, Response{Code: 500, Message: err.Error()})
		return
	}

	ctx.JSON(http.StatusOK, Response{Code: 200, Message: message})
}
